package com.example.commonmistak.apidesign.common;

import com.example.commonmistak.apidesign.anno.NoApiResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author xionggg
 * @date 2022/2/2 09:00
 */
@RestControllerAdvice
@Slf4j
public class ApiResponseAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * ApiException 自动包装为 ApiResponse
     */
    @ExceptionHandler(ApiException.class)
    public ApiResponse handleApiException(HttpServletRequest request, ApiException ex) {
        log.error("process url {} failed", request.getRequestURL(), ex);
        return ApiResponse.builder().success(false).code(ex.getErrorCode()).message(ex.getErrorMessage()).build();
    }

    /**
     * 判断哪些需要拦截
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return returnType.getParameterType() != ApiResponse.class
                && AnnotationUtils.findAnnotation(returnType.getMethod(), NoApiResponse.class) == null
                && AnnotationUtils.findAnnotation(returnType.getDeclaringClass(), NoApiResponse.class) == null;
    }

    /**
     * 包装响应体
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ApiResponse<Object> apiResponse = ApiResponse.builder().success(true).code(2000).message("SUCCESS").data(body).build();
        //restController 返回 string 时, 会被 Jackson 拦截,这里判断一下
        if (body instanceof String) {
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return objectMapper.writeValueAsString(apiResponse);
        }
        return apiResponse;
    }
}
